<template>
  <div class="search-container">
<form class="search-form" action="/">
  <van-search
    v-model="value"
    show-action

    placeholder="请输入搜索关键词"
    background="#3296fa"
    @search="onSearch"
    @cancel="onCancel"
    @focus='isResultShow=false'

  />
</form>
<!-- 搜索结果 -->
<seachResult v-if="isResultShow" :searchText='value' />
<!-- 联想建议 -->
<search-suggestion :searchText="value" v-else-if="value"  @seach='searchValue'/>
<!-- 历史记录 -->
<searchHistory :arr='searchHistories' @clear-search-history='clear' @seacht='onSearch' v-else />
  </div>
</template>

<script>
import { setItem, getItem } from '@/utils/storage'
import seachResult from '../search/components/search-result.vue'
import searchSuggestion from '../search/components/search-suggestion.vue'
import searchHistory from '../search/components/search-history.vue'
export default {

  data () {
    return {
      value: '',
      //  历史记录
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [],

      // 控制搜索结果的显示与否
      isResultShow: false
    }
  },
  components: {
    seachResult,
    searchSuggestion,
    searchHistory
  },
  methods: {
    // 添加历史记录
    onSearch (val) {
      this.value = val
      this.isResultShow = true
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // console.log(this.searchHistories);
    },
    onCancel () {
      this.$router.back() // 返回上一页（首页）
    },
    // 搜索建议添加到文本框
    searchValue (item) {
      this.value = item
      this.isResultShow = true
    },

    // 全部删除
    clear () {
      console.log(1)
      this.searchHistories = []
    }

  },
  watch: {
    searchHistories (value) {
      // 同步到本地存储
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }

  }

}
</script>

<style scoped lang='less'>

.search-container {
  	.van-search__action {
		color: #fff;
	}
	padding-top: 108px;
	.van-search__action {
		color: #fff;
	}
	 .search-form {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1;
	}
}
</style>
